package com.hiwan.system.util;

import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

public class PublicKeyReader {
	
	private static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRuhzxWuLJPhzKnFqFXhaD3LxySN8xf+wM73CgBzAc4TDLLCxPXRU3CT+6E5yYoUt3nGjK2EBqRDnuOH7NRW2E2Fieupr/IvGAyX8yJ17/Vuz84bEREB2pbyXOlzOjBhGwUYNYbSfe0eOY4ZDyHxgm4qnX2IleN8cXwcvVA9HM2wIDAQAB";
	
	/**
     * RSA最大加密明文大小 
     */  
    private static final int MAX_ENCRYPT_BLOCK = 117; 
	
    private static String RSA_JAVA = "RSA/ECB/PKCS1Padding";
    private static String RSA = "RSA";
    
	public static PublicKey get() throws Exception {
		byte[] keyBytes = Base64.decode(publicKey.toCharArray());
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance(RSA); 
        return kf.generatePublic(spec);
    }
	
	public static String encryptByPublicKey(byte[] data)throws Exception {
		Cipher cipher = Cipher.getInstance(RSA_JAVA);
		RSAPublicKey pubKey = (RSAPublicKey) PublicKeyReader.get();
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
		int inputLen = data.length;  
		ByteArrayOutputStream out = new ByteArrayOutputStream();  
		int offSet = 0;  
		byte[] cache;  
		int i = 0;  
		// 对数据分段加密  
		while (inputLen - offSet > 0) {  
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {  
				cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);  
			} else {  
				cache = cipher.doFinal(data, offSet, inputLen - offSet);  
			}  
			out.write(cache, 0, cache.length);  
			i++;  
			offSet = i * MAX_ENCRYPT_BLOCK;  
		}  
		byte[] encryptedData = out.toByteArray();  
		out.close();  
		return new String(Base64.encode(encryptedData));
	}
	
}
